package argo.hot100.review;

import java.util.Random;

public class QuickSort {

    public int[] sortArray(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return nums;
        }

        quickSort(nums, 0, nums.length - 1);
        return nums;

    }

    public void quickSort(int[] nums, int left, int right) {
        if (left < right) {
            int pivot = partition(nums, left, right);
            quickSort(nums, left, pivot - 1);
            quickSort(nums, pivot + 1, right);
        }
    }

    public int partition(int[] nums, int left, int right) {

        int pivot = new Random().nextInt(right - left) + left;
        swap(nums, pivot, right);

        int i = left;
        for (int j = left; j < right; j++) {
            if (nums[j] < nums[right]) {
                swap(nums, i, j);
                i++;
            }
        }
        swap(nums, i, right);

        return i;
    }

    public void swap(int[] nums, int inx1, int inx2) {
        int tmp = nums[inx1];
        nums[inx1] = nums[inx2];
        nums[inx2] = tmp;
    }


}
